package org.feng.service;

import org.feng.config.MySqlDynamicDatasourceConfig;
import org.feng.entity.Student;
import org.feng.repository.StudentRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * 学生业务实现
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2022年06月11日 11时11分
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentRepository studentRepository;

    @Resource
    private R2dbcEntityTemplate r2dbcEntityTemplate;

    @Override
    public Mono<Student> getById(Integer id) {
        return studentRepository.getStudentById(id);
    }

    @Override
    public Flux<Student> getStudentsByName(String merchantKey, String name) {
        return studentRepository.getStudentsByName("%" + name + "%")
                .contextWrite(context -> context.put(MySqlDynamicDatasourceConfig.MERCHANT_KEY, merchantKey));
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Mono<Student> saveStudent(Student student) {
        return studentRepository.save(student);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Flux<Student> saveStudent(List<Student> studentList) {
        return studentRepository.saveAll(studentList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Mono<Void> deleteStudent(Integer id) {
        return studentRepository.deleteById(id);
    }

    @Override
    public Flux<Student> selectStudent(Integer currentPage, String subName) {
        // 设置每页显示2条数据
        return r2dbcEntityTemplate.select(
                Query.query(Criteria.where("name").like("%" + subName + "%")).with(PageRequest.of(currentPage - 1, 2)),
                Student.class);
    }
}
